/// <license>
/// Copyright (c) 2002-2008, DotNetNuke Corporation
/// All rights reserved
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
/// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
/// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
/// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
/// of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
/// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
/// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
/// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
/// DEALINGS IN THE SOFTWARE.
/// </license>

#region Using Statements

using System;
using System.ComponentModel;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.UI.Utilities;

using DotNetNuke.Modules.Articles.Common;
using Constants = DotNetNuke.Modules.Articles.Common.Constants;
using DotNetNuke.Modules.Articles.Framework;
using DotNetNuke.ModuleToolkit.Modules.Commands;

#endregion

namespace DotNetNuke.Modules.Articles.UI.Controls
{
    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The Title skin object displays an article's Title.
    /// </summary>
    /// <history>
    /// 	[cnurse]	02/13/2006	created
    /// </history>
    /// -----------------------------------------------------------------------------
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
    ToolboxData("<{0}:Title runat=\"server\"> </{0}:Title>")]
    public class Title : 
        ArticleSkinObjectBase,
        IPostBackEventHandler,
        IModuleCommand
    {

        #region Private Members

        private string _DefaultKey;
        private string _DefaultText;
        private bool _IsLink;

        private Style _DeleteButtonStyle;
        private Style _DeletedTextStyle;
        private Style _DraftTextStyle;
        private Style _EditButtonStyle;

        private static readonly object EventCommand = new object();

        #endregion

        #region Protected Properties

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and sets the Default Css Class
        /// </summary>
        /// <history>
        ///     [cnurse]  03/18/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Browsable(false)]
        protected override String DefaultCssClass
        {
            get { return "Head"; }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the design time text to display
        /// </summary>
        /// <history>
        ///     [cnurse]  04/07/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Browsable(false)]
        protected override string DesignTimeText
        {
            get { return Constants.TEXT_Title; }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets the text to display
        /// </summary>
        /// <history>
        ///     [cnurse]  04/07/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Browsable(false)]
        protected override string DisplayText
        {
            get
            {
                //Get the Section Name Text
                string titleText = String.Empty;
                if (String.IsNullOrEmpty(DefaultKey) || DesignMode)
                    titleText = DefaultText;
                else
                    titleText = LocalizeString(DefaultKey);

                if (this.ParentArticlesModule != null && !this.ParentArticlesModule.IsAddMode
                        && (Article != null) && (Article.Title != Null.NullString))
                {
                    titleText = Article.Title;
                }
                return titleText;
            }
        }

        #endregion

        #region Public Properties

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Default Text to use if the Section has no name (to be used if no resource key is specified)
        /// </summary>
        /// <history>
        /// 	[cnurse]	08/03/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Bindable(true),
        Category("Appearance"),
        DefaultValue(""),
        Description("The Default Text to use if the Section has no name.")]
        public string DefaultText
        {
            get { return _DefaultText; }
            set { _DefaultText = value; }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Default Text to use if the Section has no name (to be used if no resource key is specified)
        /// </summary>
        /// <history>
        /// 	[cnurse]	08/03/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Bindable(true),
        Category("Localization"),
        DefaultValue(""),
        Description("The resource key to use to localize the default text.")]
        public string DefaultKey
        {
            get { return _DefaultKey; }
            set { _DefaultKey = value; }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Style to apply to the Delete Button
        /// </summary>
        /// <history>
        /// 	[cnurse]	11/01/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Category("Style"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerProperty),
        NotifyParentProperty(true),
        TypeConverter(typeof(ExpandableObjectConverter)),
        Description("The Style to apply to the Delete Button.")]
        public Style DeleteButtonStyle
        {
            get
            {
                if (_DeleteButtonStyle == null)
                    _DeleteButtonStyle = new Style();
                if (IsTrackingViewState)
                {
                    ((IStateManager)_DeleteButtonStyle).TrackViewState();
                }
                return _DeleteButtonStyle;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Style to apply to the Deleted Text
        /// </summary>
        /// <history>
        /// 	[cnurse]	11/1/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Category("Style"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerProperty),
        NotifyParentProperty(true),
        TypeConverter(typeof(ExpandableObjectConverter)),
        Description("The Style to apply to the Deleted Text.")]
        public Style DeletedTextStyle
        {
            get
            {
                if (_DeletedTextStyle == null)
                    _DeletedTextStyle = new Style();
                if (IsTrackingViewState)
                {
                    ((IStateManager)_DeletedTextStyle).TrackViewState();
                }
                return _DeletedTextStyle;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Style to apply to the Draft Text
        /// </summary>
        /// <history>
        /// 	[cnurse]	09/11/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Category("Style"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerProperty),
        NotifyParentProperty(true),
        TypeConverter(typeof(ExpandableObjectConverter)),
        Description("The Style to apply to the Draft Text.")]
        public Style DraftTextStyle
        {
            get
            {
                if (_DraftTextStyle == null)
                    _DraftTextStyle = new Style();
                if (IsTrackingViewState)
                {
                    ((IStateManager)_DraftTextStyle).TrackViewState();
                }
                return _DraftTextStyle;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// The Style to apply to the Edit Button
        /// </summary>
        /// <history>
        /// 	[cnurse]	08/07/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Category("Style"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
        PersistenceMode(PersistenceMode.InnerProperty),
        NotifyParentProperty(true),
        TypeConverter(typeof(ExpandableObjectConverter)),
        Description("The Style to apply to the Edit Button.")]
        public Style EditButtonStyle
        {
            get
            {
                if (_EditButtonStyle == null)
                    _EditButtonStyle = new Style();
                if (IsTrackingViewState)
                {
                    ((IStateManager)_EditButtonStyle).TrackViewState();
                }
                return _EditButtonStyle;
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Gets and sets whether the control is a Hyperlink
        /// </summary>
        /// <history>
        ///     [cnurse]  07/18/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Bindable(true),
        Category("Appearance"),
        DefaultValue(true),
        Description("Set whether this is a Hyperlink.")]
        public bool IsLink
        {
            get { return _IsLink; }
            set { _IsLink = value; }
        }

        #endregion

        #region Protected Methods

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderContents renders the contents of the control
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	04/07/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (DesignMode)
            {
                writer.Write(DesignTimeText);
            }
            else
            {
                if (!IsAddMode)
                {
                    RenderDeleteButton(writer);

                    RenderEditButton(writer);

                    if (IsLink && ! String.IsNullOrEmpty(DisplayText))
                    {
                        //Render Hyperlink
                        writer.AddAttribute(HtmlTextWriterAttribute.Href, ParentArticlesModule.ArticleURL(TabId, Article.ArticleId, Constants.KEY_ViewArticle));
                        writer.RenderBeginTag(HtmlTextWriterTag.A);
                        writer.Write(DisplayText);

                        //Render end of Hyperlink
                        writer.RenderEndTag();
                    }
                    else
                        writer.Write(DisplayText);

                    if (Article != null && Article.IsDraft)
                    {
                        RenderDraftWarning(writer);
                    }
                    if (Article != null && Article.IsDeleted)
                    {
                        RenderDeletedWarning(writer);
                    }
                }
                else
                    writer.Write(DisplayText);
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderEditButton renders the control's edit button
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	08/07/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected virtual void RenderDeleteButton(HtmlTextWriter writer)
        {
            bool showDelete = false;
            if (DesignMode)
                showDelete = true;
            else
                showDelete = CanDeleteArticle && !IsEditMode;

            if (showDelete && Article != null && !Article.IsDeleted)
            {
                if (DeleteButtonStyle != null)
                    DeleteButtonStyle.AddAttributesToRender(writer);

                //Render Hyperlink
                writer.AddAttribute(HtmlTextWriterAttribute.Href, Page.ClientScript.GetPostBackClientHyperlink(this, Constants.CMD_Delete, false));
                writer.AddAttribute(HtmlTextWriterAttribute.Onclick, "confirm('" + ClientAPI.GetSafeJSString(LocalizeString(Constants.CONFIRM_DeleteArticle)) + "')");
                writer.AddAttribute(HtmlTextWriterAttribute.Title, Constants.TEXT_Delete);
                writer.RenderBeginTag(HtmlTextWriterTag.A);

                //Render Image
                writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl(Constants.IMAGE_Delete));
                writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                writer.RenderBeginTag(HtmlTextWriterTag.Img);

                //Render end of Image
                writer.RenderEndTag();

                //Render end of Hyperlink
                writer.RenderEndTag();
            }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderDraftWarning renders the draft text warning
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	09/11/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void RenderDeletedWarning(HtmlTextWriter writer)
        {
            writer.WriteBreak();

            if (DeletedTextStyle != null)
                DeletedTextStyle.AddAttributesToRender(writer);

            //Render Span
            writer.RenderBeginTag(HtmlTextWriterTag.Span);

            writer.Write(LocalizeString(Constants.KEY_DeletedText));

            //Render end of Span
            writer.RenderEndTag();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderDraftWarning renders the draft text warning
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	09/11/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected void RenderDraftWarning(HtmlTextWriter writer)
        {
            writer.WriteBreak();

            if (DraftTextStyle != null)
                DraftTextStyle.AddAttributesToRender(writer);

            //Render Span
            writer.RenderBeginTag(HtmlTextWriterTag.Span);

            writer.Write(LocalizeString(Constants.KEY_DraftText));

            //Render end of Span
            writer.RenderEndTag();
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RenderEditButton renders the control's edit button
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="writer">An HtmlTextWriter</param>
        /// <history>
        /// 	[cnurse]	08/07/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        protected virtual void RenderEditButton(HtmlTextWriter writer)
        {
            bool showEdit = false;
            if (DesignMode)
                showEdit = true;
            else
                showEdit = CanEditArticle && !IsEditMode;

            if (showEdit && Article != null)
            {
                if (EditButtonStyle != null)
                    EditButtonStyle.AddAttributesToRender(writer);

                //Render Hyperlink
                writer.AddAttribute(HtmlTextWriterAttribute.Href, ParentArticlesModule.ArticleURL(TabId, Article.ArticleId, Constants.KEY_EditArticle));
                writer.AddAttribute(HtmlTextWriterAttribute.Title, Constants.TEXT_Edit);
                writer.RenderBeginTag(HtmlTextWriterTag.A);

                //Render Image
                writer.AddAttribute(HtmlTextWriterAttribute.Src, ResolveClientUrl(Constants.IMAGE_Edit));
                writer.AddAttribute(HtmlTextWriterAttribute.Border, "0");
                writer.RenderBeginTag(HtmlTextWriterTag.Img);

                //Render end of Image
                writer.RenderEndTag();

                //Render end of Hyperlink
                writer.RenderEndTag();
            }
        }

        #endregion

        #region IPostBackEventHandler Members

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// RaisePostBackEvent runs when the Delete button is clicked
        /// </summary>
        /// <history>
        ///     [cnurse]	10/07/2007	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void RaisePostBackEvent(string eventArgument)
        {
            switch (eventArgument)
            {
                case Constants.CMD_Delete:
                    OnModuleCommand(new ModuleCommandEventArgs(Constants.CMD_Delete, Constants.TYPE_Article, Article));
                    break;

            }
        }

        #endregion

        #region IModuleCommand Implementation

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Adds and removes a ModuleCommand Event Handler
        /// </summary>
        /// <history>
        ///     [cnurse]  07/21/2006  Created
        /// </history>
        /// -----------------------------------------------------------------------------
        [Category("Action"),
        Description("Raised when a command button is clicked")]
        public event ModuleCommandEventHandler ModuleCommand
        {
            add { Events.AddHandler(EventCommand, value); }
            remove { Events.RemoveHandler(EventCommand, value); }
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// OnCommand raises a Command Event
        /// </summary>
        /// <remarks>
        /// </remarks>
        /// <param name="e">A CommandEventArgs object</param>
        /// <history>
        /// 	[cnurse]	07/21/2006	created
        /// </history>
        /// -----------------------------------------------------------------------------
        public void OnModuleCommand(ModuleCommandEventArgs e)
        {
            ModuleCommandEventHandler commandHandler = (ModuleCommandEventHandler)Events[EventCommand];
            if (commandHandler != null)
                commandHandler(this, e);
        }

        #endregion

    }
}
